//
//  FZTextInputViewController.m
//  EnglishTalk
//
//  Created by CyonLeuMBP on 2017/3/22.
//  Copyright © 2017年 Feizhu Tech. All rights reserved.
//

#import "FZTextInputViewController.h"
#import <NSString+Enhanced.h>
#import <SZTextView.h>
#import "FCUtil.h"
#import "SRPersonalServices.h"
#import "SRSchoolClassServices.h"

@interface FZTextInputViewController ()<UITextViewDelegate, UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet SZTextView *textView;
@property (weak, nonatomic) IBOutlet UILabel *maxCountLabel;
@property (strong, nonatomic) NSString *inputText;
@property (weak, nonatomic) IBOutlet UILabel *helpTipLabel;
@property (strong, nonatomic) UIButton *rightButton;

@end

@implementation FZTextInputViewController


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.minInputTextCount = 0;
        self.maxInputTextCount = 400;
        self.placeholder = @"请点击输入内容";
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
    self.textView.placeholderTextColor = css.color_2;
    self.textView.font = css.fontOfH7;
    self.textView.textColor = css.color_6;
    
    self.title = self.tipTitle;
    self.textView.placeholder = self.placeholder;
    self.helpTipLabel.textColor = css.color_4;
    self.helpTipLabel.font = css.fontOfH5;
    
    if (self.inputText) {
        self.textView.text = self.inputText;
        self.maxCountLabel.text = [NSString stringWithFormat:@"%ld/%ld", (long)[self.inputText length], (long)self.maxInputTextCount];
    } else {
        self.maxCountLabel.text = [NSString stringWithFormat:@"0/%ld", (long)self.maxInputTextCount];
    }
    
    self.textView.delegate = self;
    
    if (self.isFeedback) {
        self.helpTipLabel.hidden = NO;
        [self setupNavigationBarButtonItem];
    }
    else if (self.isHomeworkComment) {
        self.helpTipLabel.hidden = YES;
        [self setupNavigationBarButtonItem];
        [self.rightButton setTitle:@"发送点评" forState:UIControlStateNormal];
    }
    else {
        self.helpTipLabel.hidden = YES;
    }
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
//    [self.textView becomeFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupNavigationBarButtonItem {
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setTitle:@"提交" forState:UIControlStateNormal];
    rightButton.titleLabel.font = css.fontOfH4;
    [rightButton setTitleColor:css.color_4 forState:UIControlStateNormal];
    
    [rightButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    rightButton.frame = CGRectMake(0, 0, 80, 44);
    [rightButton addTarget: self action: @selector(onSubmitButton:) forControlEvents: UIControlEventTouchUpInside];
    self.rightButton = rightButton;
    
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    [self setRightBarButtonItem:rightBarItem];
}


#pragma mark - Event 

- (void)onSubmitButton:(id)sender {
    WEAKSELF
    [self.textView resignFirstResponder];
    if ([self.inputText length] <= self.minInputTextCount) {
        [self showHUDHintWithText:@"请输入内容"];
        return;
    }
    if (self.isHomeworkComment) {
            //发送点评
        [SRSchoolClassServices addShowCommentShowID:self.showID comment:self.inputText type:self.homeworkType finishID:self.problem_finish_id  successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
            if (statusCode == kFZRequestStatusCodeSuccess) {
                [weakSelf showHUDHintWithText:@"发送成功"];
                if (weakSelf.didSendBlock) {
                    weakSelf.didSendBlock(weakSelf.inputText);
                }
                
                [weakSelf performSelector:@selector(doBack) withObject:nil afterDelay:2];
            } else {
                [weakSelf showHUDHintWithText:message];
            }
        } failureBlock:^(id responseObject, NSError *error) {
            [weakSelf showHUDError];

        }];
        return;
    }
    
    
    [weakSelf startProgressHUD];
    [SRPersonalServices sendFeedbackWithContent:self.inputText successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf stopProgressHUD];
        if (statusCode == kFZRequestStatusCodeSuccess) {
             [weakSelf showHUDHintWithText:@"反馈成功"];
            
            [weakSelf performSelector:@selector(doBack) withObject:nil afterDelay:3];
        } else {
            [weakSelf showHUDHintWithText:message];
        }
        
    } failureBlock:^(id responseObject, NSError *error) {
        [weakSelf showHUDError];
    }];
}

- (void)setPreText:(NSString *)preText {
    _preText = preText;
    
    self.inputText = preText;
}

- (void)doBack {
    if ([self.inputText length] > 0 && [self.inputText length] < self.minInputTextCount){
            //若小于10 则提示
        WEAKSELF
        NSString *message = [NSString stringWithFormat:@"%@至少输入%d个字", self.tipTitle, (int)self.minInputTextCount];
        
        UIAlertView *alertView = [UIAlertView alertViewWithTitle:nil message:message cancelButtonTitle:@"继续编辑" didDismissBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {
                    //退出
                weakSelf.inputText = nil;
                if (weakSelf.didChangeInputTextBlock) {
                    weakSelf.didChangeInputTextBlock(self.inputText);
                }
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
        } otherButtonTitles:@"退出", nil];
        
        [alertView show];
        
//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"继续编辑" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            
//        }];
//        
//        UIAlertAction *exitAction = [UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            [weakSelf.navigationController popViewControllerAnimated:YES];
//        }];
//        
//        [alertController addAction:alertAction];
//        [alertController addAction:exitAction];
//        
//        [self presentViewController:alertController animated:YES completion:nil];
    } else {
        [super doBack];
    }
}

#pragma mark - UITextViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.textView resignFirstResponder];
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
    
}
- (void)textViewDidEndEditing:(UITextView *)textView {
//    NSLog(@"textViewDidEndEditing:%@", textView.text);

}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    NSString * originText = textView.text;
    if (([originText length] + [text length]) > self.maxInputTextCount) {
        NSString *message = [NSString stringWithFormat:@"最多输入%ld个字", (long)self.maxInputTextCount];
        [self showHUDHintWithText:message];
        return NO;
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView {
//    NSLog(@"textViewDidChange:%@", textView.text);
    self.inputText = [textView.text stringToTrimWhiteSpace];

    if ([self.inputText length] > self.maxInputTextCount) {
        NSInteger maxLength = self.maxInputTextCount * 2;
        NSArray *lengths = [FCUtil stringLengthWithString:self.inputText maxLength:maxLength];
        if([lengths count] > 0 && [[lengths objectAtIndex:0] integerValue] > maxLength){
            NSString * text = [self.inputText substringToIndex:[[lengths objectAtIndex:1] integerValue]];
            if([NSThread isMainThread]){
                self.textView.text = text;
                self.inputText = text;
                self.maxCountLabel.text = [NSString stringWithFormat:@"%ld/%ld", (long)[self.inputText length], (long)self.maxInputTextCount];
                
                if (self.didChangeInputTextBlock) {
                    self.didChangeInputTextBlock(self.inputText);
                }
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.textView.text = text;
                    self.inputText = text;
                    self.maxCountLabel.text = [NSString stringWithFormat:@"%ld/%ld", (long)[self.inputText length], (long)self.maxInputTextCount];
                    
                    if (self.didChangeInputTextBlock) {
                        self.didChangeInputTextBlock(self.inputText);
                    }
                });
            }
            
            NSString *message = [NSString stringWithFormat:@"最多输入%ld个字", (long)self.maxInputTextCount];
            [self showHUDHintWithText:message];
        }
    } else {
        self.maxCountLabel.text = [NSString stringWithFormat:@"%ld/%ld", (long)[self.inputText length], (long)self.maxInputTextCount];

        if (self.didChangeInputTextBlock) {
            self.didChangeInputTextBlock(self.inputText);
        }
    }
}



@end
